package com.hb.core.exception;

import com.hb.core.base.BaseResponse;
import com.hb.core.constant.Code;
import com.hb.core.enums.CommCode;
import org.springframework.http.ResponseEntity;

/**
 * @description:
 * @projectName: zhb-frame-build
 * @author: zhouhaizhi
 * @createTime: 2021/9/2 16:11
 * @version:1.0
 */
abstract class AbstractExceptionHandler {

    static final String ERROR_MSG_WITH_EXCEPTION_NAME = "服务器出现[%S]异常";

    ResponseEntity build(Exception e) {
        String customErrMsg = String.format(ERROR_MSG_WITH_EXCEPTION_NAME, e.getClass().getSimpleName());
        return build(e, customErrMsg);
    }

    ResponseEntity build(Exception e, String customErrMsg) {
        Code code;
        if (e instanceof ServiceException) {
            ServiceException sourceException = (ServiceException) e;
            code = Code.newInstance(sourceException.getCode().getCode(), sourceException.getCode().getName(),
                    sourceException.getErrorMessage());
        } else {
            code = Code.newInstance(CommCode.ERROR.getCode(), CommCode.ERROR.getName(), customErrMsg);
        }

        BaseResponse baseResponse = new BaseResponse(String.valueOf(code.getCode()), code.getMessage());
        return ResponseEntity.ok(baseResponse);
    }
}
